<template>
  <div class="page-box">
    <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="120px" class="demo-ruleForm">
      <el-form-item label="密码" prop="pass">
        <el-input v-model="ruleForm.pass" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="确认密码" prop="checkPass">
        <el-input v-model="ruleForm.checkPass" type="password" autocomplete="off" />
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-input v-model.number="ruleForm.age" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
const ruleFormRef = ref(null)
const ruleForm = reactive({
  pass: '',
  checkPass: '',
  age: '',
})
// 判断年龄
const checkAge = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('请输入年龄'))
  }
  if (!Number.isInteger(value)) {
    callback(new Error('Please input digits'))
  } else {
    if (value < 18) {
      callback(new Error('年龄必须大于18'))
    } else {
      callback()
    }
  }
}
// 判断密码
const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback('请输入密码')
  } else {
    if (ruleForm.checkPass !== '') {
      if (!ruleFormRef.value) {
        return
      }
      ruleFormRef.value.validateField('checkPass', () => null) // 去验证checkPass字段
    }
    callback()
  }
}
// 判断两个输入的密码是否相等
const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请重新输入密码'))
  } else if (value !== ruleForm.pass) {
    callback(new Error('密码输入不一致!'))
  } else {
    callback()
  }
}

// 验证规则
const rules = reactive({
  pass: [{ validator: validatePass, trigger: 'blur' }],
  checkPass: [{ validator: validatePass2, trigger: 'blur' }],
  age: [
    { required: true, message: '必填' },
    { validator: checkAge, trigger: 'blur' },
  ],
})

// 提交
const submitForm = (formEl) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('submit!')
    } else {
      console.log('error submit!')
      return false
    }
  })
}

// 重置
const resetForm = (formEl) => {
  if (!formEl) {
    return
  }
  formEl.resetFields()
}
</script>

<style scoped></style>
